// pages/user/user.js
import { OrderDetail } from 'orderDetail-model.js'
import { hex_md5 } from '../../utils/md5.js'
var order = new OrderDetail();

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
      userInfo: {},
      orderList:null,
      address:'',
      showAddressId:'',
      loadDone:false,
      allowClick: true,
      addressUrl:'',
      show_bottom_address:false,
      totalpay:0,
      soldoutList:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      console.log(options)
      let id = options.orderId;
      let storeNo = options.storeNo || wx.getStorageSync('storeNo');
      this.setData({
        storeNo,
        orderId:id
      });
      this._loadData();
  },
  onPageScroll(e){
    console.log(e)
    let status = false
    if(e.scrollTop > 50){
        status = true
    }else{
        status = false
    }
    this.setData({
        show_bottom_address:status
    })

  },
  _loadData(callback,type){
    let { storeNo, orderId } = this.data;
    let that = this, goodsNum = 0;
    let parames = {
      "orderId": orderId,
      "storeNo": storeNo
    }
    if (!(type || type == 'pulldown')) {
        wx.showLoading({
            title: '加载中',
        })
    }
    order.getDetailList(parames,res=>{
        if (res.status){
            if (res.data.userAddressId){
                this.getAddrss(res.data.userAddressId)
             }
            that.setData({
                orderList: res.data ? res.data : "",
                loadDone:true,
                totalpay: Number(res.data.orderPrice) + Number(res.data.postage)
            })
            callback && callback()
            wx.hideLoading()
        }
    });

  },
//   显示的时候判断是否有地址更新
  onShow(){
      let id = this.data.showAddressId
      if(id != ''){
          this.getAddrss(id)        
      }
  },
  //跳转到地址页面
  onselAddress(){
    let { orderList }=this.data;
    let addressUrl = "";
    if (orderList.orderStatus == 'W') {
        addressUrl = '/pages/selAddress/selAddress?type=sel&orderId=' + orderList.orderId + '&addressId=' + orderList.userAddressId;
     wx.navigateTo({
       url: addressUrl
     })
    } else {
      return;
    }

  },
  //   封装根据id获取地址
  getAddrss(id){
       let addressId = {
          "id": '' + id
       }
       order.getUserAddressById(addressId, resAddress => {
          if (resAddress.status) {
              this.setData({
                  address: resAddress.data,
                  loadDone: true                  
              })
          }
       })
  },
  getBackAddressId(id) {
      this.setData({
          showAddressId: id,
          'orderList.userAddressId':id
      })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this._loadData(res=>{
        wx.stopPullDownRefresh()
    },'pulldown')
  },
  wxPay(){
        let that = this
        let data = this.data
        let wxuid = wx.getStorageSync('wxUid');
        let id = this.data.orderId
        let allowClick = this.data.allowClick
        let params = {
            "wxuid": wxuid,
            "orderId": id
        }
        this.setData({
            allowClick: false
        })
        
        if (!allowClick) {
            console.log('多点拦截')
            return
        } else if (data.orderList.orderStatus != 'S' && (data.orderList.userAddressId == '' || data.address.status == 1)){
            order.showMyTip({ _this: this, title: "请先选择地址" }); 
            that.setData({
                allowClick: true
            })       
        }else{
            wx.showLoading({
                title: '加载中',
            })
            console.log('click')
            order.wxPay(params,res=>{
                wx.hideLoading()                        
              console.log(res)
                if (res.status){
                  let data = res.data
                  console.log('res', res, res.data, 'prepay_id=' + data.miniPaySign)
                    if (data.result_code == "SUCCESS" && data.return_code == "SUCCESS"){
                        console.log('success')
                        wx.requestPayment({
                            'timeStamp': '' + data.miniTimeStamp,
                            'nonceStr': '' + data.miniNonceStr,
                            'package': 'prepay_id=' +data.prepay_id,
                            'signType': 'MD5',
                            'paySign': '' + data.miniPaySign,
                            'success': function (result) {
                                console.log('pay', result)
                                order.reduceGoodsStock({
                                    orderId: id
                                }, reduce => {
                                    that._loadData();
                                })
                            },
                            'fail': function (result) {
                                that.setData({
                                    allowClick: true
                                })
                            
                            }
                        })
                    } else if (data.stockList && data.stockList.length > 0) {
                        console.log(data.stockList)
                        this.setData({
                            soldoutList: data.stockList,
                            allowClick: true
                        })
                    }
                }else{
                    wx.hideLoading()                                            
                    order.showMyTip({ _this: this, title: "服务器错误" });                   
                    this.setData({
                        allowClick: true
                    })
                }
            })
        }
  },
  soldoutBack() {
      this.setData({
          soldoutList: null,
          allowClick: true

      })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

})